package com.xqc.utils;

import com.xqc.bean.TableDefinitionBean;
import com.xqc.config.PropertiesUtil;
import com.xqc.constants.XqcConstants;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class MapperXmlUtils {

    public static void createMapperXml(String tableName){
        String className = ClassUtils.createClassNameSuff(tableName)+"Mapper";
        //mapper接口的路径
        String mapperPth = PropertiesUtil.getPackageName()+"."+XqcConstants.MAPPER_DIR;
        StringBuilder builder = new StringBuilder("");
        builder.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n")
                .append("<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\" >\n")
                .append("<mapper namespace=\"")
                .append(mapperPth)
                .append(".")
                .append(className)
                .append("\" >\n");
        List<TableDefinitionBean> tableDefinitionBeans = TableUtils.tableDefinitionBeans(tableName);
        builder.append(selectAll(tableDefinitionBeans,tableName));
        builder.append(selectByPrimaryKey(tableDefinitionBeans,tableName));
        builder.append("</mapper>");
        try {
            String fileName = FileUtils.createFilePath(XqcConstants.MAPPER_DIR)+"/"+className+ ".xml";
            FileOutputStream fis = new FileOutputStream(new File(fileName));
            fis.write(builder.toString().getBytes());
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(builder.toString());
    }

    /**
     * 查询所有
     * @param tableName
     * @return
     */
    private static String selectAll(List<TableDefinitionBean> tableDefinitionBeans,String tableName){
        //entity类路径
        String entityPth = PropertiesUtil.getPackageName()+"."+XqcConstants.ENTITY_DIR;
        StringBuilder sqlBuild = new StringBuilder("\t</select ");
        sqlBuild.append("id=\"")
                .append("selectAll")
                .append("\" ")
                .append("parameterType=\"")
                .append(entityPth)
                .append("\" ")
                .append(">\n")
                .append("\t\tselect \n\t\t\t");
        int size = tableDefinitionBeans.size();
        int count = 0;
        for (TableDefinitionBean tableDefinitionBean : tableDefinitionBeans) {
            String fieldName = tableDefinitionBean.getFieldName();
            count ++;
            //最后一个
            if(count == size){
                sqlBuild.append(fieldName).append("\n\t\t");
            }else{
                sqlBuild.append(fieldName).append(",\n\t\t\t");
            }
        }
        sqlBuild.append(" from \n\t\t\t")
                .append(tableName)
                .append("\n\t")
                .append(" where \n\t\t")
                .append(allCondition(tableDefinitionBeans))
                .append("</select>\n\n");
        return sqlBuild.toString();
    }

    /**
     * 根据主键查询
     * @param tableDefinitionBeans
     * @param tableName
     * @return
     */
    private static String selectByPrimaryKey(List<TableDefinitionBean> tableDefinitionBeans,String tableName){
        //entity类路径
        String entityPth = PropertiesUtil.getPackageName()+"."+XqcConstants.ENTITY_DIR;
        StringBuilder sqlBuild = new StringBuilder("\t</select ");
        sqlBuild.append("id=\"")
                .append("selectByPrimaryKey")
                .append("\" ")
                .append("parameterType=\"")
                .append(entityPth)
                .append("\" ")
                .append(">\n")
                .append("\t\tselect \n\t\t\t");
        int size = tableDefinitionBeans.size();
        int count = 0;
        String primaryKey = null;
        for (TableDefinitionBean tableDefinitionBean : tableDefinitionBeans) {
            String fieldName = tableDefinitionBean.getFieldName();
            count ++;
            //最后一个
            if(count == size){
                sqlBuild.append(fieldName).append("\n\t\t");
            }else{
                sqlBuild.append(fieldName).append(",\n\t\t\t");
            }
            //判断是不是主键
            if("PRI".equals(tableDefinitionBean.getKey())){
                primaryKey = fieldName;
            }
        }
        sqlBuild.append(" from \n\t\t\t")
                .append(tableName)
                .append("\n\t\t")
                .append(" where\n\t\t\t")
                .append(primaryKey)
                .append(" = ")
                .append("#{")
                .append(primaryKey)
                .append("}")
                .append("\n\t</select>\n\n");
        return sqlBuild.toString();
    }

    /**
     * condition
     * @param tableDefinitionBeans
     * @return
     */
    private static String allCondition(List<TableDefinitionBean> tableDefinitionBeans){
        StringBuilder sqlBuild = new StringBuilder("");
        for (TableDefinitionBean tableDefinitionBean : tableDefinitionBeans) {
            String fieldName = tableDefinitionBean.getFieldName();
            String fieldType = TableUtils.subFieldType(tableDefinitionBean.getFieldType());
            sqlBuild.append("<if test=\"").append(fieldName);
            if("varchar".equals(fieldType) || "text".equals(fieldType)){
                sqlBuild.append(" != null and !='' \">\n\t\t\t");
            }else{
                sqlBuild.append(" != null \">\n\t\t\t");
            }
            sqlBuild.append(fieldName)
                    .append(" = #{")
                    .append(fieldName)
                    .append("}\n\t\t")
                    .append("</if>\n\t\t");
        }
        return sqlBuild.toString();
    }

}
